package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //过滤器类型：pre前置过滤器，route路由过滤器，post后置过滤器，error错误处理过滤器
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //顺序号，确定过滤器的位置
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        //针对当前请求进行判断，判断是否要执行下面的过滤代码
        //demo:调用后台商品服务需要检查权限，其他服务可以直接访问
        /*获得RequestContext对象--调用静态方法获取上下文对象*/
        RequestContext context = RequestContext.getCurrentContext();
        String serviceId = context.get(FilterConstants.SERVICE_ID_KEY)
                                    .toString();
        return "item-service".equals(serviceId);
    }

    @Override
    public Object run() throws ZuulException {
        //过滤代码，检查用户的权限，放行或直接返回登录提示
        //1.获取请求上下文对象RequestContext
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //2.接收token参数
        String token = request.getParameter("token");
        //3.进行token校验
        //if (token.length()==0||token==null||token.isEmpty())
        if (StringUtils.isBlank(token)){
            //判断没有token值，阻止继续调用
            context.setSendZuulResponse(false);
            //直接返回响应
            String json = JsonResult.err()
                    .code(400)
                    .msg("not login")
                    .toString();
            context.addOriginResponseHeader("Content-Type","application/json;charset=UTF-8");
            context.setResponseBody(json);
        }
        //zuul在当前版本此返回值没有实际意义
        return null;
    }
}
